﻿//NorManager - OpenTTD Dedicated server manager
//Copyright (C) 2014 Tomáš Bosek

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.IO;

namespace NorManager
{
    /// <summary>
    /// Logger class singleton. Used for printing on the screen and to the log file simultaneously.
    /// </summary>
    public class Logger
    {
        public static Logger Instance { get { if (logger == null) { logger = new Logger(); } return logger; } }
        private static Logger logger = null;

        public static string Version
        {
            get
            {
                return System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).ProductVersion;
            }
        }

        private FileStream log = null;
        private StreamWriter writer;

        private Logger()
        {
            if (!Directory.Exists("log"))
                Directory.CreateDirectory("log");

            DateTime now = DateTime.Now;
            string name = String.Format("{0}{1}{2}{3}{4}", new object[]{now.Month, now.Day, now.Hour, now.Minute, now.Second});
            log = new FileStream("log/" + name + ".log", FileMode.Create);

            writer = new StreamWriter(log);
            writer.AutoFlush = true;

            Log("Log file created.");

            Log("NorManager v."+Version);
        }

        /// <summary>
        /// Prints message.
        /// </summary>
        public void Log(string message)
        {
            Log(message, ConsoleColor.White);
        }
        /// <summary>
        /// Prints message with specified color(in console only).
        /// </summary>
        public void Log(string message, ConsoleColor color)
        {
            if (message == null || message.Length == 0)
                return;

            if (color != Console.ForegroundColor)
                Console.ForegroundColor = color;

            DateTime now = DateTime.Now;
            string line = String.Format("[{0}.{1}.{2} {3}:{4}:{5}] {6}", new object[] { now.Day, now.Month, now.Year, now.Hour, now.Minute, now.Second, message });
            Console.WriteLine(line);

            if (log != null)
                writer.WriteLine(line);
        }
    }
}
